package cc.smarnet.caihou.phone.sanhuoin;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cc.smarnet.caihou.IPConfig;

import cc.smarnet.caihou.LoginActivity;
import cc.smarnet.caihou.R;
import cc.smarnet.caihou.cheng.Bluetooth_Scale;
import cc.smarnet.caihou.cheng.DeviceListActivity;
import cc.smarnet.caihou.cheng.MainDemoActivity;
import cc.smarnet.caihou.cheng.ScaleView;
import cc.smarnet.caihou.entity.TFlowerTagIn2;
import cc.smarnet.caihou.entity.TFlowerTagInMain2Page;
import cc.smarnet.caihou.util.DateUtil;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;

/**
 * 散货入库---生成入库单
 */
public class HarvesInActivity extends AppCompatActivity {
    private String TAG = "HarvesInActivity";
    private ImageButton imageButton;
    private Spinner ffromSpinner;
    private Spinner sourceBaseSpinner;//来源基地
    private Spinner sourceGreenhouseSpinner;//来源大棚
    private Spinner varietySpinner;//采收品种
    private TextView varietyCodeTextView;//品种编码;
    private Spinner packingSpecificationsSpinner;//打包规格
    private Spinner classesSpinner;//等级
    private Spinner flowerPoleLengthSpinner;//花杆长度
    private Spinner houseSpinner;
    private EditText tagNumEditText;//入库数量;
    private EditText sortTimeEditText;//分拣日期;
    private EditText sealerEditText;
    private EditText frompeopleEdit;
    private Button confirmButton;
    private ProgressBar progressBar;

    private View neibu;
    private View waibu;


    private String token;

    List<String> ffromList = new ArrayList<>();
    List<String> sourceBaseList = new ArrayList<>();
    List<String> sourceGreenhouseList = new ArrayList<>();
    List<String> varietyList = new ArrayList<>();
    List<String> varietyCodeList = new ArrayList<>();
    List<String> packingSpecificationsList = new ArrayList<>();
    List<String> classesList = new ArrayList<>();
    List<String> flowerPoleLengthList = new ArrayList<>();

    List<String> sourceBaseIdList = new ArrayList<>();
    List<String> sourceGreenhouseIdList = new ArrayList<>();
    List<String> storehouseList = new ArrayList<>();

    private String storeHouse;
    private String storeHouseId;
    private ArrayList<String> storeHouseList = new ArrayList<>();
    private ArrayList<String> storeHouseIDList = new ArrayList<>();

    private String ffrom;
    private String sealer;
    private String frompeople;
    private String sourceBaseId;//来源基地id
    private String sourceGreenhouseId;//来源大棚id
    private String variety;//采收品种
    private String varietyCode;//品种编码
    private String packingSpecifications;//打包规格
    private String classes;//等级
    private String flowerPoleLength;//花杆长度
    private BigDecimal tagNum;//入库数量
    private String sortTime;//分拣日期

    int mYear, mMonth, mDay;

    //    private final String basePath = "/sys/dict/getDictItems";
    private final String basePath = "/sys/api/getDictItems";


    //-----------------秤-----
    //-----------------秤-----
    //-----------------秤-----
    final Boolean SendMoudle = true;  //  这个表示是连接称重模块
    Boolean bisClosed = false;
    public ScaleView scaleView;
    Bundle bundle;
    public Button mButton_SearchBluetooth;

    /**
     * BLE ն
     */
    private BluetoothAdapter mBluetoothAdapter;
    /**
     * дBLE ն
     */
    private Bluetooth_Scale mBl_Scale = null;
    private BluetoothDevice device;
    Handler mHandler;
    Boolean b_scaleIsConnect = Boolean.FALSE;
    MainDemoActivity.SCALENOW scalenow = new MainDemoActivity.SCALENOW();
    String BluetoothAddress;
    //-----------------秤-----
    //-----------------秤-----end----
    //-----------------秤-----


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.harves_in);

        getSupportActionBar().hide();//隐藏标题栏

        initViews();
        progressBar.setVisibility(View.GONE);

        sortTime = DateUtil.currentDate();
//        sortTimeEditText.setText(sortTime);//设置默认的分拣日期

        getToken();

        /*
         * 获取基地的数据并设置在spinner中，然后再获取大棚的数据并设置在spinner。
         * 只有先有了基地的数据才能获取到相应大棚的数据
         * */
        getSourceBase();
        getVariety();//获取采收品种
        getPackingSpecifications();//获取打包规格
        getClasses();//获取等级
        getFlowerPoleLength();// 获取花杆长度

        getDate();// 获取当前的日期
        // 选择分拣日期的监听
  /*      sortTimeEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerDialog datePickerDialog = new DatePickerDialog(HarvesInActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int month, int day) {
                                mYear = year;
                                mMonth = month;
                                mDay = day;
                                String transMonth = String.format("%02d", mMonth + 1);// 如果月份小于10的话进行补0
                                String transDay = String.format("%02d", mDay);// 如果日小于10的话进行补0
                                sortTime = mYear + "-" + transMonth + "-" + transDay;
                                sortTimeEditText.setText(sortTime);
                            }
                        }, mYear, mMonth, mDay);
                datePickerDialog.show();
            }
        });*/
        // 点击确认按钮的监听
        confirmButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (ffrom.equals("外部")  && sealerEditText.getText().toString().equals("")) {
                    AlertDialog alertDialog = new AlertDialog.Builder(HarvesInActivity.this).create();
                    alertDialog.setMessage("请输入供应商！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                }
                if (frompeopleEdit.getText().toString().equals("")) {
                    AlertDialog alertDialog = new AlertDialog.Builder(HarvesInActivity.this).create();
                    alertDialog.setMessage("请输入采摘/收购人！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                }
                // 获取入库数量
                if (tagNumEditText.getText().toString().equals("")) {
                    AlertDialog alertDialog = new AlertDialog.Builder(HarvesInActivity.this).create();
                    alertDialog.setMessage("请连接蓝牙获取入库重量！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                } else {
                    tagNum = new BigDecimal(tagNumEditText.getText().toString());
                }

             /*   // 获取分拣日期
                if (sortTimeEditText.getText().toString().equals("点击选择日期")) {
                    AlertDialog alertDialog = new AlertDialog.Builder(HarvesInActivity.this).create();
                    alertDialog.setMessage("请选择分拣日期！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                }*/

                // 新增入库信息
                addWarehouse();
            }
        });
        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tagNumEditText.setEnabled(false);


//============秤==========start======================
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 1:
                        bundle = msg.getData();
                        GetWeight(bundle.getByteArray("weight"));
                        scaleView.setUnit(scalenow.sUnit);
                        if (scalenow.bOverFlag) {
                            scaleView.setText("over----");
                        } else {
                            scaleView.setText(scalenow.sformatNetWeight);
                        }

                        scaleView.setZero(scalenow.bZeroFlag);
                        scaleView.setStable(scalenow.bWeiStaFlag);
                        break;
                    case 2:
                        if (msg.arg1 < 2) {
                            scaleView.setText(getString(R.string.NoConnect));
                            b_scaleIsConnect = Boolean.FALSE;
                        } else {
                            b_scaleIsConnect = Boolean.TRUE;
                            if (SendMoudle) {
                                scaleView.setText("已连接");
                                mBl_Scale.write("RN1\r\n".getBytes());    //模块需要发送RN1表示连续读净重
                            }
                        }
                        break;

                }
            }
        };
        mBluetoothAdapter.enable();
        mBl_Scale = new Bluetooth_Scale(this, mHandler);
        scaleView = (ScaleView) findViewById(R.id.scaleView1);


//        mButton_Zero = (Button) findViewById(R.id.Button_Zero);
//        mButton_Tare = (Button) findViewById(R.id.Button_Tare);
//        mButton_Unit = (Button) findViewById(R.id.Button_Unit);
        mButton_SearchBluetooth = (Button) findViewById(R.id.Button_Search);
        mButton_SearchBluetooth.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent serverIntent = new Intent(HarvesInActivity.this, DeviceListActivity.class);
                startActivityForResult(serverIntent, 0);
            }
        });

      /*  mButton_Zero.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if ((mBl_Scale != null) && b_scaleIsConnect) {
                    Log.d(TAG, "Zero");
                    mBl_Scale.write("SZ09\r\n".getBytes());
                }
            }
        });


        mButton_Tare.setOnClickListener(new View.OnClickListener() {

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if ((mBl_Scale != null) && b_scaleIsConnect) {
                    mBl_Scale.write("ST07\r\n".getBytes());
                }
            }
        });
        mButton_Unit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if ((mBl_Scale != null) && b_scaleIsConnect) {
                    mBl_Scale.write("SU06\r\n".getBytes());
                }
            }
        });*/
        //============秤==========end======================


        try {
            Thread.sleep(1000);// 线程暂停1秒，单位毫秒
            fromSpinner();
            getStoreHouse();
        } catch (Exception e) {

        }

    }

    public void initViews() {
        imageButton = findViewById(R.id.warehouse_add_return);
        ffromSpinner = findViewById(R.id.ffrom_spinner);
        sourceBaseSpinner = findViewById(R.id.warehouse_add_sourceBase_spinner);
        sourceGreenhouseSpinner = findViewById(R.id.warehouse_add_sourceGreenhouse_spinner);
        varietySpinner = findViewById(R.id.warehouse_add_variety_spinner);
        houseSpinner = findViewById(R.id.storehouse_spinner);
        varietyCodeTextView = findViewById(R.id.warehouse_add_varietyCode_textView);
        packingSpecificationsSpinner = findViewById(R.id.warehouse_add_packingSpecifications_spinner);
        classesSpinner = findViewById(R.id.warehouse_add_classes_spinner);
        flowerPoleLengthSpinner = findViewById(R.id.warehouse_add_flowerPoleLength_spinner);
        tagNumEditText = findViewById(R.id.warehouse_add_tagNum_editText);
        frompeopleEdit = findViewById(R.id.frompeople_edit);
//        sortTimeEditText = findViewById(R.id.warehouse_add_sortTime_editText);
        sealerEditText = findViewById(R.id.sealer_editText);
        confirmButton = findViewById(R.id.warehouse_confirm_add_button);
        progressBar = findViewById(R.id.warehouse_add_progressBar);

        neibu = findViewById(R.id.neibu);
        waibu = findViewById(R.id.waibu);
    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }

    // 获取基地
    public void getSourceBase() {
        progressBar.setVisibility(View.VISIBLE);
        String url = IPConfig.baseUrl + "/flower/plantingBase/getAllBase";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(HarvesInActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(HarvesInActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                sourceBaseList.add(name);
                                sourceBaseIdList.add(jsonObj.getString("id"));
                            }

                            if (sourceBaseIdList.size() > 0) {// 如果sourceBaseIdList有值的话为sourceBaseSpinner赋值，然后获取第一个基地下大棚的数据
                                sourceBaseId = sourceBaseIdList.get(0);//设置默认的基地的id
                                sourceBaseSpinner();
                                getSourceGreenhouse(sourceBaseIdList.get(0));
                            }
                        }
                    }
                });
    }

    // 获取大棚
    public void getSourceGreenhouse(String sourceBaseId) {
        String url = IPConfig.baseUrl + "/flower/flowerPlantingGreenhouse/queryByParentId/" + sourceBaseId;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        /*Toast.makeText(HarvesInActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(HarvesInActivity.this, LoginActivity.class);
                        startActivity(intent);*/
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);
                        sourceGreenhouseList.clear();
                        confirmButton.setClickable(true);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);
                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                sourceGreenhouseList.add(name);
                                sourceGreenhouseIdList.add(jsonObj.getString("id"));
                            }
                            if (sourceGreenhouseList.size() > 0) {
                                sourceGreenhouseId = sourceGreenhouseIdList.get(0);//设置默认大棚的id
                                sourceGreenhouseSpinner();
                            }
                        } else {
                            // 如果没有取到大棚的数据，那么弹窗提示，在弹窗中点击了确定按钮后，并且使确定按钮不可用
                            AlertDialog alertDialog = new AlertDialog.Builder(HarvesInActivity.this).create();
                            alertDialog.setMessage("所选基地无大棚信息，无法进行新增入库信息操作！");
                            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    sourceGreenhouseSpinner();
                                    confirmButton.setClickable(false);
                                }
                            });
                            alertDialog.show();
                        }
                    }
                });
    }

    // 获取采收品种
    public void getVariety() {
        String url = IPConfig.baseUrl + "/flower/flowerVariety/queryNames";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(HarvesInActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(HarvesInActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                varietyList.add(name);
                                // 获取品种编码
                                String code = jsonObj.getString("code");
                                varietyCodeList.add(code);
                            }

                            if (varietyList.size() > 0) {
                                variety = varietyList.get(0);// 设置默认的采收品种
                                varietyCode = varietyCodeList.get(0);// 设置默认的品种编码
                                varietyCodeTextView.setText(varietyCode);
                                varietySpinner();
                            }
                        }
                    }
                });
    }

    // 获取打包规格
    public void getPackingSpecifications() {
        String url = IPConfig.baseUrl + basePath;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .addParams("dictCode", "planting_packing_specifications")
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(HarvesInActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(HarvesInActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONArray jsonArray = JSONArray.parseArray(response);
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObj = jsonArray.getJSONObject(i);
                            String name = jsonObj.getString("text");
                            packingSpecificationsList.add(name);
                        }
                        packingSpecifications = packingSpecificationsList.get(0);
//                        if (packingSpecificationsList.size() > 0) {
//                            packingSpecifications = packingSpecificationsList.get(0);// 设置默认的打包规格
//                            packingSpecificationsSpinner();
//                        }
                    }
                });
    }

    // 获取花卉等级
    public void getClasses() {
        String url = IPConfig.baseUrl + basePath;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .addParams("dictCode", "planting_flower_level")
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(HarvesInActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(HarvesInActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONArray jsonArray = JSONArray.parseArray(response);
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObj = jsonArray.getJSONObject(i);
                            String name = jsonObj.getString("text");
                            classesList.add(name);
                        }

                        if (classesList.size() > 0) {
                            classes = classesList.get(0);// 设置默认的打包规格
                            classesSpinner();
                        }
                    }
                });
    }

    // 获取花杆长度
    public void getFlowerPoleLength() {
        String url = IPConfig.baseUrl + basePath;
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .addParams("dictCode", "planting_flower_pole")
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(HarvesInActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(HarvesInActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONArray jsonArray = JSONArray.parseArray(response);

                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jsonObj = jsonArray.getJSONObject(i);
                            String name = jsonObj.getString("text");
                            flowerPoleLengthList.add(name);
                        }
                        flowerPoleLength = flowerPoleLengthList.get(0);// 设置默认的花杆长度

//                        if (flowerPoleLengthList.size() > 0) {
//                            flowerPoleLength = flowerPoleLengthList.get(0);// 设置默认的花杆长度
//                            flowerPoleLengthSpinner();
//                        }
                    }
                });
    }


    // 获取仓库下拉
    public void getStoreHouse() {
        String url = IPConfig.baseUrl + "/flower/flowerStorehouse/listByPsn";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
//                .addParams("name", name)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(HarvesInActivity.this, "Token失效，请重新登录", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonarray = JSON.parseArray(result);
                            storeHouseList.clear();
                            storeHouseIDList.clear();
                            for (int i = 0; i < jsonarray.size(); i++) {
                                JSONObject jsonObj = jsonarray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                String id3 = jsonObj.getString("code");
                                storeHouseList.add(name);
                                storeHouseIDList.add(id3);
                            }
                            if (jsonarray.size() >= 0) {
                                storeHouse = storeHouseList.get(0);// 默认第一个仓库
                                storeHouseId = storeHouseIDList.get(0);
                            } else {
                                storeHouse = "";
                                storeHouseId = "";
                            }
                            houseSpinner();
                        } else {
                            Toast.makeText(HarvesInActivity.this, "获取仓库失败" + Boolean.parseBoolean(JSON.parseObject(response).getString("message")), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    //仓库下拉
    public void houseSpinner() {
        ArrayAdapter placeArrayAdapter = new ArrayAdapter(this, R.layout.my_spinner_item, storeHouseList);
        placeArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        houseSpinner.setAdapter(placeArrayAdapter);
        houseSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                storeHouse = storeHouseList.get(i);
                storeHouseId = storeHouseIDList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //
    public void fromSpinner() {
        ffromList.add("内部");
        ffromList.add("外部");

        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, ffromList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        ffromSpinner.setAdapter(adapter);
        ffromSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                ffrom = ffromList.get(i);
                if (ffrom.equals("内部")) {
                    neibu.setVisibility(View.VISIBLE);
                    waibu.setVisibility(View.GONE);
                } else {
                    neibu.setVisibility(View.GONE);
                    waibu.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //来源基地的spinner
    public void sourceBaseSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, sourceBaseList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sourceBaseSpinner.setAdapter(adapter);
        sourceBaseSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                sourceBaseId = sourceBaseIdList.get(i);
                getSourceGreenhouse(sourceBaseId);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //来源大棚的spinner
    public void sourceGreenhouseSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, sourceGreenhouseList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sourceGreenhouseSpinner.setAdapter(adapter);
        sourceGreenhouseSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                sourceGreenhouseId = sourceGreenhouseIdList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //采收品种的spinner
    public void varietySpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, varietyList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        varietySpinner.setAdapter(adapter);
        varietySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                variety = varietyList.get(i);

                varietyCode = varietyCodeList.get(i);
                varietyCodeTextView.setText(varietyCode);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //打包规格的spinner
//    public void packingSpecificationsSpinner() {
//        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, packingSpecificationsList);
//        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//        packingSpecificationsSpinner.setAdapter(adapter);
//        packingSpecificationsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
//                packingSpecifications = packingSpecificationsList.get(i);
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> adapterView) {
//            }
//        });
//    }

    //等级的spinner
    public void classesSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, classesList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        classesSpinner.setAdapter(adapter);
        classesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                classes = classesList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //花杆长度的spinner
    public void flowerPoleLengthSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, flowerPoleLengthList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        flowerPoleLengthSpinner.setAdapter(adapter);
        flowerPoleLengthSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                flowerPoleLength = flowerPoleLengthList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }


    // 新增入库信息
    public void addWarehouse() {
        progressBar.setVisibility(View.VISIBLE);
        confirmButton.setClickable(false);
        if (StringUtils.isBlank(ffrom)) {
            Toast.makeText(HarvesInActivity.this, "请选择来源", Toast.LENGTH_SHORT).show();
            return;
        }
        if (ffrom.equals("外部") && sealerEditText.getText() == null) {
            Toast.makeText(HarvesInActivity.this, "请输入供应商", Toast.LENGTH_SHORT).show();
            return;
        }
        if (frompeopleEdit.getText() == null) {
            Toast.makeText(HarvesInActivity.this, "请输入采摘人", Toast.LENGTH_SHORT).show();
            return;
        }
        if (tagNumEditText.getText() == null) {
            Toast.makeText(HarvesInActivity.this, "请连接蓝牙获取入库重量", Toast.LENGTH_LONG).show();
            return;
        }
        sealer = sealerEditText.getText().toString();
        frompeople = frompeopleEdit.getText().toString();
        tagNum =new BigDecimal(tagNumEditText.getText().toString());
        if(tagNum.compareTo(BigDecimal.ZERO)<=0){
            Toast.makeText(HarvesInActivity.this, "重量不可小于或等于0", Toast.LENGTH_SHORT).show();
            return;
        }

        TFlowerTagInMain2Page flowerTagInMain2Page = new TFlowerTagInMain2Page();
        List<TFlowerTagIn2> in2List = new ArrayList<>();

        flowerTagInMain2Page.setFfrom(ffrom);
        flowerTagInMain2Page.setSealer(sealer);
        flowerTagInMain2Page.setFrompeople(frompeople);
        flowerTagInMain2Page.setSourceBase(sourceBaseId);
        flowerTagInMain2Page.setSourceGreenhouse(sourceGreenhouseId);
        flowerTagInMain2Page.setStorehouse(storeHouseId);
        flowerTagInMain2Page.setSortTime(new Date());
        flowerTagInMain2Page.setInType("手工入库");

        TFlowerTagIn2 flowerTagIn2 = new TFlowerTagIn2();
        flowerTagIn2.setSourceBase(sourceBaseId);
        flowerTagIn2.setSourceGreenhouse(sourceGreenhouseId);
        flowerTagIn2.setVariety(variety);
        flowerTagIn2.setVarietyCode(varietyCode);
        flowerTagIn2.setStorehouse(storeHouseId);
        flowerTagIn2.setPackingSpecifications(packingSpecifications);
        flowerTagIn2.setFlowerPoleLength(flowerPoleLength);
        flowerTagIn2.setClasses(classes);
        flowerTagIn2.setTagNum(tagNum);
        flowerTagIn2.setSortTime(new Date());
        flowerTagIn2.setInType("手工入库");

        in2List.add(flowerTagIn2);
        flowerTagInMain2Page.settFlowerTagIn2List(  JSONArray.toJSONString(in2List) );
        flowerTagInMain2Page.setVariety(   JSONArray.toJSONString(in2List)  );

        String requestJsonString = JSON.toJSONString(flowerTagInMain2Page);


        String url = IPConfig.baseUrl + "/flower/tFlowerTagInMain2/add2";
        OkHttpUtils
                .postString()
                .addHeader("X-Access-Token", token)
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(requestJsonString.toString())
                .build()
                .readTimeOut(100000)
                .connTimeOut(100000)
                .writeTimeOut(100000)
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        confirmButton.setClickable(true);
                        Toast.makeText(HarvesInActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(HarvesInActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);
                        confirmButton.setClickable(true);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            AlertDialog alertDialog = new AlertDialog.Builder(HarvesInActivity.this).create();
                            alertDialog.setMessage("入库信息新增成功");
                            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
//                                    Intent intent = new Intent(HarvesInActivity.this, HarvesInActivity.class);
//                                    startActivity(intent);
                                    finish();
                                }
                            });
                            alertDialog.setCanceledOnTouchOutside(false);
                            alertDialog.show();
                        }
                    }
                });
    }

    // 获取当前日期
    public void getDate() {
        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
    }


    //============秤==========start======================
    //============秤==========start======================
    //============秤==========start======================
    @Override
    public void onConfigurationChanged(Configuration config) {
        super.onConfigurationChanged(config);
        Log.e(TAG, "++ ON ConfigurationChanged ++");
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mBl_Scale != null) {
            Log.e(TAG, "+ Not null +");
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mBl_Scale.getState() == Bluetooth_Scale.STATE_NONE) {
                // Start the Bluetooth chat services
                if (BluetoothAddress != null) {
                    Log.e(TAG, "+ Address Not null +");
                    // Get the BluetoothDevice object
                    // device= mBluetoothAdapter.getRemoteDevice(BluetoothAddress);
                    // if(device!=null)
                    // {
                    // mBl_Scale.connect(device);
                    // }
                }
            }
        }
    }

    @SuppressLint("SimpleDateFormat")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (resultCode == RESULT_OK) {
                    connectDevice(data);
                }
                break;

        }
    }

    private void connectDevice(Intent data) {
        // Get the device MAC address

        mBl_Scale.stop();        // ȶϿ ǰ       ,Ȼ    ʱһ        ,  ֤ǰ    Ѿ  Ͽ ,     ֱ     Ӳ      ӵ     һ   豸,   ʧ  ,
        BluetoothAddress = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        if (BluetoothAddress.length() > 0) {
            // Get the BluetoothDevice object
            device = mBluetoothAdapter.getRemoteDevice(BluetoothAddress);
            if (device != null) {
                mBl_Scale.connect(device);
                if(mBl_Scale.getState() == 2  ){
                    mButton_SearchBluetooth.setText("传输中");
                    mButton_SearchBluetooth.setBackgroundColor(Color.GREEN);
                }
                if(mBl_Scale.getState() == 3  ){
                    Toast.makeText(this,"已连接",Toast.LENGTH_SHORT).show();
                    mButton_SearchBluetooth.setBackgroundColor(Color.GREEN);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (mBl_Scale != null) mBl_Scale.stop();
        bisClosed = true;
        super.onDestroy();
        //  System.exit(0);
    }

    public static int _dec(int l, int m, int n) {
        int a = l, b = m, c = 1;
        while (b != 0) {
            while ((b & 1) == 0) {
                b >>= 1;
                a = (int) ((long) a * a % n);
            }
            b--;
            c = (int) ((long) a * c % n);
        }
        return c;
    }

    static byte ASCII2Bin(byte strdata) {
        if ((strdata <= '9') && (strdata >= '0')) return (byte) (strdata - '0');
        else if ((strdata <= 'z') && (strdata >= 'a')) return (byte) (strdata - 'a' + 10);
        else return (byte) (strdata - 'A' + 10);
    }

    static float HctWeightDecryption(byte buf[]) {
        int r[] = new int[4];
        int ret;
        r[0] = (ASCII2Bin(buf[0]) & 0xf) * 0x1000 + (ASCII2Bin(buf[1]) & 0xf) * 0x100
                + (ASCII2Bin(buf[2]) & 0xf) * 0x10 + (ASCII2Bin(buf[3]) & 0xf);
        r[1] = (ASCII2Bin(buf[4]) & 0xf) * 0x1000 + (ASCII2Bin(buf[5]) & 0xf) * 0x100
                + (ASCII2Bin(buf[6]) & 0xf) * 0x10 + (ASCII2Bin(buf[7]) & 0xf);
        r[2] = (ASCII2Bin(buf[8]) & 0xf) * 0x1000 + (ASCII2Bin(buf[9]) & 0xf) * 0x100
                + (ASCII2Bin(buf[10]) & 0xf) * 0x10 + (ASCII2Bin(buf[11]) & 0xf);
        r[3] = (ASCII2Bin(buf[12]) & 0xf) * 0x1000 + (ASCII2Bin(buf[13]) & 0xf) * 0x100
                + (ASCII2Bin(buf[14]) & 0xf) * 0x10 + (ASCII2Bin(buf[15]) & 0xf);
        ret = ((_dec(r[0], 47653, 39917) & 0xff) << 24) + (_dec(r[1], 47653, 39917) & 0xff) * 0x10000 + (_dec(r[2], 47653, 39917) & 0xff) * 0x100 + _dec(r[3], 47653, 39917);
        float f = Float.intBitsToFloat(ret);
        return f;
    }

    void GetWeight(byte[] databuf) {
        int i, j, offset = 6;
        String ShowFmtTab[] = {"%1$8.0f", "%1$8.1f", "%1$8.2f", "%1$8.3f", "%1$8.4f", "%1$8.5f", "%1$8.6f", "%1$8.6f", "%1$8.6f"};
        boolean StartFalg = false;
        scalenow.bZeroFlag = true;
        scalenow.bOverFlag = false;
        scalenow.bWeiStaFlag = false;
        switch (databuf[0]) {
            case 'o':
            case 'O':
                scalenow.bOverFlag = true;
                break;
            case 'u':
            case 'U':
                scalenow.bWeiStaFlag = false;
                offset = 6;    //6
                break;
            case 's':
            case 'S':
                scalenow.bWeiStaFlag = true;
                break;
        }
        /*byte[] weightbuf=new byte[16];
        for(i=0;i<16;i++) {
            weightbuf[i]=(byte)(databuf[offset+i]);
        }
        scalenow.formatNetWeight=HctWeightDecryption(weightbuf);
        j=(databuf[offset+16]-'0')/3;
        if((j>=0)&&(j<=9))scalenow.sformatNetWeight=String.format(ShowFmtTab[(databuf[offset+16]-'0')/3], scalenow.formatNetWeight);
        for(j=0;j<6;j++)
        {
            if(databuf[17+j+offset]<0x20)
            {
                break;
            }
        }
        scalenow.sUnit=new String(databuf,17+offset,j);
        */
        if (databuf[5] == '-') offset = 5;
        for (i = 0; i < 14; i++) {
            if (databuf[i + offset] == '\'') databuf[i + offset] = '.';
            if (StartFalg) {
                if (((databuf[i + offset] > '9') || (databuf[i + offset] < '.')) && (!((databuf[i + offset] == ' ') && (databuf[i + offset + 1] <= '9')))) {
                    break;
                }
            } else if ((databuf[i + offset] >= '0') && (databuf[i + offset] <= '9')) {
                StartFalg = true;
                if (databuf[i + offset] != '0') scalenow.bZeroFlag = false;
            }
        }
        scalenow.sformatNetWeight = new String(databuf, offset, i);

//        Toast.makeText(this, scalenow.sformatNetWeight, Toast.LENGTH_LONG).show();
//        Toast.makeText(this, scalenow.sformatNetWeight, Toast.LENGTH_LONG).show();
//处理成数字
        if (StringUtils.isNotBlank(scalenow.sformatNetWeight)) {
            String xNew = scalenow.sformatNetWeight.replaceAll("\\+", "");
            xNew = xNew.replaceAll(" ", "");
            tagNumEditText.setText(xNew);
        } else {
            tagNumEditText.setText(0);
        }

        for (j = 0; j < 6; j++) {
            if (databuf[i + j + offset] < 0x20) {
                break;
            }
        }
        scalenow.sUnit = new String(databuf, i + offset, j);

    }

    public static class SCALENOW {
        public float formatNetWeight;
        public String sformatNetWeight = "0";
        public String sUnit = "0";
        public boolean bWeiStaFlag;
        public boolean bZeroFlag;
        public boolean bOverFlag;
    }
//============秤==========end======================

}